# Moths - an environment for mathy calculations
# Copyright (C) 2006 Mike Sutjipto
# Licensed under the GPL

module Moths
  
  # One of the 'irreducable' (is that a word?) types of expressions
  # i.e. evaluating it returns back itself
  # This just represents a number
  #
  # TODO need to distinguish between different types of numbers (real, complex, etc)
  #      and in general, this will be part of the larger typing system
  #      as a whole
  #
  class Number < Expression
    @num_type
    @num

    attr_reader :num, :num_type

    def initialize(num_type, num)
      @num_type = num_type
      @num = num
      @precedence = 7
    end

    def eval(env)
      return self
    end

    def to_s
      return @num.to_s
    end

    def +(r)
      case r
        when Matrix
          return r.map { |e| e + self }

        when Number
          return Number.new(self.num_type, self.num + r.num)

        else
          raise MothsError, 'Addition undefined for these types'
      end
    end

    def -(r)
      case r
        when Matrix
          return r.map { |e| e - self}

        when Number
          return Number.new(self.num_type, self.num - r.num)

        else
          raise MothsError, 'Subtraction undefined for these types'
      end
    end

    def *(r)
      case r
        when Matrix
          return r.map { |e| e * self}

        when Number
          return Number.new(self.num_type, self.num * r.num)

        else
          raise MothsError, 'Multiplication undefined for these types'
      end
    end

    def /(r)
      case r
        when Matrix
          return self * r.inverse

        when Number
          return Number.new(self.num_type, self.num / r.num)

        else
          raise MothsError, 'Division undefined for these types'
      end
    end

    def **(r)
      case r
        when Matrix
          raise MothsError, 'Exponentiation undefined for these types'
          
        when Number
          return Number.new(self.num_type, self.num ** r.num)
          
        else
          raise MothsError, 'Exponentation undefined for these types'
      end
    end
  end
  
end
